package com.ruoyi.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.tencentUtils.CommonUtils;
import com.ruoyi.system.domain.AppDitch;
import com.ruoyi.system.domain.AppTradeRecord;
import com.ruoyi.system.domain.AppUser;
import com.ruoyi.system.domain.AppUserEquipment;
import com.ruoyi.system.service.IAppDitchService;
import com.ruoyi.system.service.IAppTradeRecordService;
import com.ruoyi.system.service.IAppUserEquipmentService;
import com.ruoyi.system.service.IAppUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/app/user")
@Api("APP用户接口")
public class ForAppUserController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IAppUserService userService;
    @Autowired
    private IAppUserEquipmentService userEquipmentService;
    @Autowired
    private IAppDitchService ditchService;
    @Autowired
    private IAppTradeRecordService tradeRecordService;

    @RequestMapping(value = "getUserInfo", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("获取当前登录用户信息")
    public AjaxResult getUserInfo() {
        AppUser appUser = userService.selectAppUserByUserId(getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("user", appUser);
        // 更新设备登录信息
        AppUserEquipment userEquipment = userEquipmentService.getOneByUserId(getUserId());
        if (userEquipment != null) {
            userEquipment.setLastLoginTime(new Date());
            userEquipmentService.updateById(userEquipment);
        }
        return AjaxResult.ok(0, "", map);
    }

    @PostMapping("updateAuthIdNumber")
    @ApiOperation("身份认证")
    public AjaxResult updateAuthIdNumber(@ApiIgnore @ApiParam("真实姓名") String realName,
                                         @ApiIgnore @ApiParam("身份证号码") String idNumber) {
        // 校验身份证的方法
        if (!CommonUtils.isValidIDCard(idNumber)) {
            return AjaxResult.error(-1, "身份证号码格式错误！");
        }
        AppUser currUser = new AppUser();
        currUser.setIdNumber(idNumber);
        currUser.setRealName(realName);
        currUser.setAuthState(1);
        userService.update(currUser, new QueryWrapper<AppUser>().eq("user_id", getUserId()));
        return AjaxResult.ok(0, "身份认证成功", null);
    }

    @PostMapping("cancellation")
    @ApiOperation("注销用户")
    public AjaxResult cancellation(@ApiIgnore @ApiParam("userId") Long userId) {
        AppUser currUser = new AppUser();
        currUser.setState(2L);
        userService.update(currUser, new QueryWrapper<AppUser>().eq("user_id", getUserId()));

        return AjaxResult.ok(0, "注销成功", null);
    }

    @PostMapping("getInfoById")
    @ApiOperation("根据userId获取用户信息")
    public AjaxResult getInfoById(@ApiParam("用户userId") @RequestParam Long userId) {
        AppUser userEntity = userService.getById(userId);
        userEntity.setUsername(CommonUtils.decodeNickname(userEntity.getUsername()));
        userEntity.setPassword(null);
        userEntity.setPayPass(null);

        Map<String, Object> map = new HashMap<>();
        map.put("user", userEntity);
        return AjaxResult.ok(0, "", map);
    }

    @PostMapping(value = "getUserInviteInfo")
    @ApiOperation("获取用户邀请信息")
    public AjaxResult getUserInviteInfo() {
        QueryWrapper<AppDitch> ditchWrapper = new QueryWrapper<>();
        ditchWrapper.eq("user_id", getUserId());
        AppDitch ditchEntity = ditchService.getOne(ditchWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("inviteInfo", ditchEntity);
        return AjaxResult.ok(0, "", map);
    }

    @PostMapping("getUserList")
    @ApiOperation("查询用户列表")
    public AjaxResult getUserList(@ApiParam("查询关键词，account") @RequestParam String searchValue) {
        QueryWrapper<AppUser> wrapper = new QueryWrapper<>();
        wrapper.eq("isadd", 1);
        wrapper.and(q -> q.eq("mobile", searchValue).or().eq("account", searchValue));
        AppUser userEntity = userService.getOne(wrapper);
        if (userEntity == null) {
            return AjaxResult.error(-1, "不存在此账号用户！");
        }
        userEntity.setPassword(null);
        userEntity.setPayPass(null);
        Map<String, Object> map = new HashMap<>();
        map.put("user", userEntity);
        return AjaxResult.ok(0, "", map);
    }


    @PostMapping("saveLastLoginTime")
    @ApiOperation("保存最后登录时间")
    public AjaxResult saveLastLoginTime(@ApiParam("userId") Long userId, @ApiParam("格式为：设备id,设备名称") String equipmentId) {
        AppUser userEntity = new AppUser();
        userEntity.setLastLoginTime(new Date());
        userService.update(userEntity, new QueryWrapper<AppUser>().eq("user_id", getUserId()));

        if (StringUtils.isNotBlank(equipmentId)) {
            String[] equipmentInfo = equipmentId.split(",");

            AppUserEquipment equipment = new AppUserEquipment();
            equipment.setEquipmentId(equipmentInfo[1]);
            AppUserEquipment userEquipment = userEquipmentService.getOne(equipment);
            Date nowTime = new Date();
            if (null == userEquipment) {
                userEquipment = new AppUserEquipment();
                userEquipment.setCrtTime(nowTime);
                userEquipment.setUserId(userEntity.getUserId());
                userEquipment.setEquipmentId(equipmentInfo[0]);
                if (equipmentInfo.length > 1) {
                    userEquipment.setEquipmentId(equipmentInfo[1]);
                    userEquipment.setEquipmentName(equipmentInfo[0]);
                }
                userEquipment.setLastLoginTime(nowTime);
                userEquipment.setStatus(0);
                userEquipmentService.save(userEquipment);
            } else {
                if (1 == userEquipment.getStatus()) {
                    return AjaxResult.error(-10001, "用户设备已被禁止，请联系管理员或客服！");
                }
                userEquipment.setUserId(userEntity.getUserId());
                userEquipment.setLastLoginTime(nowTime);
                userEquipmentService.updateById(userEquipment);
            }
        }
        return AjaxResult.ok(0, "", null);
    }


    @PostMapping("withdrawal")
    @ApiOperation("提现")
    public AjaxResult withdrawal(
            @ApiParam("提现金额") BigDecimal money,
            @ApiParam("收款地址") String address) {
        if (money.compareTo(BigDecimal.valueOf(10l)) < 0)
            return AjaxResult.error(-1, "提现金额最低 10 USDT!");
        return userService.applyWithdrawal(getUserId(), money, address);
    }


    @PostMapping("updateUserUsdtAddress")
    @ApiOperation("绑定收款地址")
    public AjaxResult updateUserUsdtAddress(@ApiParam("收款地址") String collectionAddress) {
        return userService.updateUserUsdtAddress(getUserId(), collectionAddress);
    }

    @PostMapping("submitRecharge")
    @ApiOperation("提交充值")
    public AjaxResult submitRecharge(@ApiParam("收款地址") String account,
                                     @ApiParam("存入金额") BigDecimal money,
                                     @ApiParam("打款地址") String payAddress,
                                     @ApiParam("打款凭证") String paymentVoucher) {
        AppTradeRecord tradeRecord = new AppTradeRecord();
        tradeRecord.setUserId(getUserId()); // 用户id
        tradeRecord.setType(0);
        tradeRecord.setAccount(account); // 收款地址
        tradeRecord.setPaymentVoucher(paymentVoucher);
        tradeRecord.setPayAddress(payAddress);
        tradeRecord.setMoney(money.setScale(2, BigDecimal.ROUND_HALF_UP)); // 存入金额
        tradeRecord.setAuditType(1); // 审核状态，0：未提交，1：待确认，2：已确认，3：未通过
        tradeRecordService.insertAppTradeRecord(tradeRecord);

        return AjaxResult.ok(0, "提交充值成功", null);
    }

    @PostMapping("setPayPassword")
    @ApiOperation("设置支付密码")
    public AjaxResult setPayPassword(@ApiParam("登录密码") @RequestParam String userPassword,
                                     @ApiParam("支付密码") @RequestParam String payPassword) {
        AppUser userEntity = userService.getById(getUserId());
        if (!userPassword.equals(userEntity.getPassword())) {
            return AjaxResult.error(-1, "用户登录密码校验错误！");
        }

        AppUser userRecord = new AppUser();
        userRecord.setPayPass(payPassword);
        userService.update(userRecord, new QueryWrapper<AppUser>().eq("user_id", getUserId()));

        return AjaxResult.ok(0, "设置支付密码成功", null);
    }

    @PostMapping("getTransactionRecords")
    @ApiOperation("获取交易记录")
    public AjaxResult getTransactionRecords(@ApiParam("页数") @RequestParam(defaultValue = "1") int page,
                                            @ApiParam("条数") @RequestParam(defaultValue = "10") int limit) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("page", page);
        params.put("limit", limit);

        QueryWrapper<AppTradeRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", getUserId());
        wrapper.orderByDesc("create_time");

        Page<AppTradeRecord> obj = tradeRecordService.page(new Page<>(page, limit), wrapper);
        Map<String, Object> res = Maps.newHashMap();
        res.put("totalPage", obj.getTotal());
        res.put("list", obj.getRecords());
        res.put("pageSize", obj.getSize());
        res.put("page", obj.getCurrent());
        res.put("total", obj.getTotal());

        return AjaxResult.ok(0, "获取交易记录", res);
    }


}
